<?php
class WPaymentPagseguroAuthorize extends USystemWorklet
{	
	public function accessRules()
	{
		return array(
			array('deny', 'users'=>array('?'))
		);
	}
	
	public function run($items,$orderId=null,$options=array())
	{
		include_once(dirname(__FILE__).'/../components/UPagseguro.php');
		$options = array(
			'email' => $this->param('business')
		);
		$p = new UPagseguro($options);
		$p->addField('ref_transacao',$orderId);
		
		foreach($items as $key=>$val)
		{
			if($val['price'] < 0)
				$p->addField('extras',$p->formatAmount($val['price']*$val['quantity']));
			elseif(is_array($val))
			{
				$p->addField('item_id_'.($key+1),$orderId.($key+1));
				foreach($val as $k=>$v)
				{
					$fKey = '';
					switch($k)
					{
						case 'name':
							$fKey = 'item_descr';
							$v = strlen($v)>=100
								? txt()->utf8substr($v,0,97).'...'
								: $v;
							break;
						case 'price':
							$fKey = 'item_valor';
							$v = $p->formatAmount($v);
							break;
						case 'quantity':
							$fKey = 'item_quant';
							break;
					}
					if($fKey)
					{
						$fKey.= '_'.($key+1);
						$p->addField($fKey,$v);
					}
				}
			}
		}
		
		wm()->get('base.init')->addToJson(array(
			'content' => array(
				'keepDisabled' => true,
				'append' => $p->getForm(),
				'focus' => true,
			),
		));
	}
}